package com.rongxue.rzzf;

import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientHelper{

	public static String doHttp(String urlStr,String charSet,Object parameters, String timeOut) throws Exception{
		String responseString="";
		PostMethod xmlpost;
		int statusCode = 0;
		HttpClient httpclient = new HttpClient();
		httpclient.setConnectionTimeout(new Integer(timeOut).intValue());
		xmlpost = new PostMethod(urlStr);
		httpclient.getParams().setParameter(
				HttpMethodParams.HTTP_CONTENT_CHARSET, charSet);
		try{
			//组合请求参数
			List<NameValuePair> list=new ArrayList<NameValuePair>();
			Method[] ms=parameters.getClass().getMethods();
			for(int i=0;i<ms.length;i++){
				Method m=ms[i];
				String name=m.getName();
				if(name.startsWith("get")){
					String param=name.substring(3,name.length());
					param=param.substring(0,1).toLowerCase()+param.substring(1,param.length());
					if(param.equals("class")){
						continue;
					}
					Object value="";
					try {
						value = m.invoke(parameters, null);
						NameValuePair nvp=new NameValuePair(param,value.toString());
						list.add(nvp);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						throw e;
					}
				}
			}
			NameValuePair[] nvps=new NameValuePair[list.size()];
			xmlpost.setRequestBody(list.toArray(nvps));
			statusCode = httpclient.executeMethod(xmlpost);
			responseString = xmlpost.getResponseBodyAsString();
			if(statusCode<HttpURLConnection.HTTP_OK || statusCode>=HttpURLConnection.HTTP_MULT_CHOICE){
				System.err.println("失败返回码[" + statusCode + "]");
				throw new Exception("请求接口失败，失败码[ "+ statusCode +" ]");
			}
		}catch(IOException e){
			e.printStackTrace();
			System.err.println(e.toString());
			throw e;
		}
		return responseString;
	}







	public static String sendTest(String url, String param) throws Exception {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("Content-Type", "application/x-fox");
			conn.setRequestProperty("connection", "close");
			conn.setRequestProperty("user-agent", "gSOAP/2.7");
			conn.setRequestProperty("dont_redispatch", "1");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "gbk"));
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "gbk"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

}
